package com.pinyoumei.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pinyoumei.base.TaotaoResult;
import com.pinyoumei.constans.Constants;
import com.pinyoumei.mapper.TbPayMapper;
import com.pinyoumei.pay.service.PayService;
import com.pinyoumei.pojo.TbPay;
import com.pinyoumei.service.component.JedisSingleClient;
import com.pinyoumei.utils.IDUtils;
import com.pinyoumei.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;



@Slf4j
@RestController
public class PayServiceImpl implements PayService {
	
	@Autowired
	private TbPayMapper payMapper;
	
	@Autowired
	private JedisSingleClient jedisClient;
	
	@Value("${alipay.app_id}")
	private String app_id;
	
	@Value("${alipay.merchant_private_key}")
	private String merchant_private_key;
	
	@Value("${alipay.public_key}")
	private String public_key;
	
	@Value("${alipay.notify_url}")
	private String notify_url;
	
	@Value("${alipay.return_url}")
	private String return_url;
	
	@Value("${alipay.sign_type}")
	private String sign_type;
	
	@Value("${alipay.charset}")
	private String charset;
	
	@Value("${alipay.gatewayUrl}")
	private String gatewayUrl;


	
	/**
	 * 创建支付令牌
	 * @param pay
	 * @return
	 * localhost:8889/pay/createPayToken?payToken=
	 */
	@RequestMapping("/createPayToken")
	public String createPayToken(@RequestBody TbPay pay) {
		//1. 创建支付信息
		pay.setCreated(new Date());
		pay.setUpdated(new Date());
		Integer result=payMapper.insert(pay);
		if(result<=0){
			TaotaoResult taotaoResult=TaotaoResult.build(201, "支付信息创建失败", "");
			return JsonUtils.objectToJson(taotaoResult);
		}
		//2. 生成token
		String payToken=IDUtils.generatePayToken();
		//3. 存入redis
		jedisClient.set(payToken, JsonUtils.objectToJson(pay),Constants.TOKEN_PAY_TIME);
		//4. 返回token  
		TaotaoResult taotaoResult=TaotaoResult.build(200, "支付信息创建成功",payToken);
		return JsonUtils.objectToJson(taotaoResult);
	}

	
	/**
	 * 使用支付令牌查找支付信息
	 * @param payToken
	 * @return
	 * localhost:8889/pay/getPayByToken
	 */
	@RequestMapping("/getByToken")
	public String getByToken(@RequestParam("payToken")String payToken) {
		log.info("appId:{},payToken:{}",app_id,payToken);
		//1. 参数验证
		if(StringUtils.isEmpty(payToken)){
		    TaotaoResult result=TaotaoResult.build(600,"token不能为空", "");
			return JsonUtils.objectToJson(result);
		}
		//2. 判断token有效期,使用token获取支付信息
		String payJson=jedisClient.get(payToken);
		if(StringUtils.isEmpty(payJson)){
			 TaotaoResult result=TaotaoResult.build(600,"token已失效,未找到支付信息", "");
			 return JsonUtils.objectToJson(result);
		}
		//3. 支付下单
		TbPay pay=JsonUtils.jsonToPojo(payJson,TbPay.class);
		//4. 对接支付宝,返回html标签给客户端,是一个form表单用于提交支付
		// 获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, app_id,merchant_private_key, "json",charset,public_key,sign_type);
		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(return_url);
		alipayRequest.setNotifyUrl(notify_url);
		// 商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = pay.getOrderid();
		// 付款金额，必填 企业金额
		String total_amount = pay.getPrice() + "";
		// 订单名称，必填
		String subject = "品优美购物";
		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\","
				// + "\"body\":\""+ body +"\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求
		try {
			String payHtml = alipayClient.pageExecute(alipayRequest).getBody();
			TaotaoResult result=TaotaoResult.build(200,"请求支付宝成功",payHtml);
			return JsonUtils.objectToJson(result);
		} catch (Exception e) {
			TaotaoResult result=TaotaoResult.build(201,"支付异常","");
			return JsonUtils.objectToJson(result);
		}
		
	}

}
